package com.sttk.secreconeclick.bookkeep.fragment;

import android.graphics.Color;
import android.os.Bundle;
import android.view.View;

import androidx.recyclerview.widget.LinearLayoutManager;

import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.data.BarData;
import com.github.mikephil.charting.data.BarDataSet;
import com.github.mikephil.charting.data.BarEntry;
import com.github.mikephil.charting.data.PieData;
import com.github.mikephil.charting.data.PieDataSet;
import com.github.mikephil.charting.data.PieEntry;
import com.github.mikephil.charting.formatter.IndexAxisValueFormatter;
import com.github.mikephil.charting.formatter.PercentFormatter;
import com.github.mikephil.charting.utils.ColorTemplate;
import com.lzb.basic.utils.SPUtil;
import com.sttk.secreconeclick.bookkeep.BaseNoModelFragment;
import com.sttk.secreconeclick.bookkeep.Content;
import com.sttk.secreconeclick.bookkeep.R;
import com.sttk.secreconeclick.bookkeep.adapter.RankAdapter;
import com.sttk.secreconeclick.bookkeep.bean.AccountBookBean;
import com.sttk.secreconeclick.bookkeep.bean.BillBean;
import com.sttk.secreconeclick.bookkeep.bean.BillTypeBean;
import com.sttk.secreconeclick.bookkeep.bean.RankBean;
import com.sttk.secreconeclick.bookkeep.bean.YearlyStatisticsBean;
import com.sttk.secreconeclick.bookkeep.databinding.FragmentStatisticsBinding;
import com.sttk.secreconeclick.bookkeep.utils.AppSpUtils;
import com.sttk.secreconeclick.bookkeep.utils.MyBillReader;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

/**
 * 统计页面Fragment
 * 实现支出和收入账单统计，支持按今年、本月、本周筛选数据
 */
public class StatisticsFragment extends BaseNoModelFragment<FragmentStatisticsBinding> implements View.OnClickListener {

    // 统计类型
    private static final int TYPE_EXPENDITURE = 0;
    private static final int TYPE_INCOME = 1;

    // 时间范围
    private static final int TIME_WEEK = 0;
    private static final int TIME_MONTH = 1;
    private static final int TIME_YEAR = 2;

    private int currentType = TYPE_EXPENDITURE; // 当前统计类型
    private int currentTimeRange = TIME_YEAR; // 当前时间范围

    private RankAdapter rankAdapter;
    private List<BillBean> allBills = new ArrayList<>();

    @Override
    protected int onCreate() {
        return R.layout.fragment_statistics;
    }

    @Override
    protected void initView() {
        initChart();
        initRecyclerView();
        initClickListeners();

        // 默认选中支出和今年
        updateTypeSelection();
        updateTimeSelection();
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.tvExpenditure) {//支出
            currentType = TYPE_EXPENDITURE;
            updateTypeSelection();
            updateCharts();
        } else if (id == R.id.tvIncome) {//收入
            currentType = TYPE_INCOME;
            updateTypeSelection();
            updateCharts();
        } else if (id == R.id.tvWeek) {//周
            currentTimeRange = TIME_WEEK;
            updateTimeSelection();
            updateCharts();
        } else if (id == R.id.tvMonth) {//月
            currentTimeRange = TIME_MONTH;
            updateTimeSelection();
            updateCharts();
        } else if (id == R.id.tvYear) {//年
            currentTimeRange = TIME_YEAR;
            updateTimeSelection();
            updateCharts();
        }
    }

    @Override
    protected void initData() {
        loadBillData();
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
            loadBillData();
        }
    }

    private void initChart() {
        // 初始化柱状图
        mDataBinding.barChart.getDescription().setEnabled(false);
        mDataBinding.barChart.setDrawGridBackground(false);
        mDataBinding.barChart.setDrawBarShadow(false);
        mDataBinding.barChart.setDrawValueAboveBar(true);
        mDataBinding.barChart.setPinchZoom(false); // 禁止缩放
        mDataBinding.barChart.setScaleEnabled(false); // 禁止滑动和缩放
        mDataBinding.barChart.setDoubleTapToZoomEnabled(false); // 禁止双击缩放
        mDataBinding.barChart.setDragEnabled(false); // 禁止拖拽滑动
        mDataBinding.barChart.setDrawGridBackground(false);

        XAxis xAxis = mDataBinding.barChart.getXAxis();
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
        xAxis.setDrawGridLines(false);
        xAxis.setGranularity(1f);

        mDataBinding.barChart.getAxisLeft().setDrawGridLines(false);
        mDataBinding.barChart.getAxisLeft().setEnabled(false); // 不显示左侧Y轴
        mDataBinding.barChart.getAxisRight().setEnabled(false); // 不显示右侧Y轴
        mDataBinding.barChart.getLegend().setEnabled(false);

        // 初始化饼图
        mDataBinding.pieChart.getDescription().setEnabled(false);
        mDataBinding.pieChart.setUsePercentValues(true);
        mDataBinding.pieChart.setDrawHoleEnabled(true);
        mDataBinding.pieChart.setHoleColor(Color.WHITE);
        mDataBinding.pieChart.setTransparentCircleColor(Color.WHITE);
        mDataBinding.pieChart.setTransparentCircleAlpha(110);
        mDataBinding.pieChart.setHoleRadius(58f);
        mDataBinding.pieChart.setTransparentCircleRadius(63f);
        mDataBinding.pieChart.setDrawCenterText(true);
        mDataBinding.pieChart.setCenterText(currentType == TYPE_EXPENDITURE ? "支出占比" : "收入占比");
        mDataBinding.pieChart.setEntryLabelTextSize(10f);
        mDataBinding.pieChart.setRotationEnabled(true);
        mDataBinding.pieChart.setHighlightPerTapEnabled(true);
        mDataBinding.pieChart.getLegend().setEnabled(true);
        mDataBinding.pieChart.setDrawEntryLabels(true);
        mDataBinding.pieChart.setEntryLabelColor(Color.BLACK);
    }

    private void initRecyclerView() {
        rankAdapter = new RankAdapter();
        mDataBinding.rvRankList.setLayoutManager(new LinearLayoutManager(mContext));
        mDataBinding.rvRankList.setAdapter(rankAdapter);

    }

    private void initClickListeners() {
        // 支出/收入切换
        mDataBinding.tvExpenditure.setOnClickListener(this);
        mDataBinding.tvIncome.setOnClickListener(this);

        // 时间范围切换
        mDataBinding.tvWeek.setOnClickListener(this);
        mDataBinding.tvMonth.setOnClickListener(this);
        mDataBinding.tvYear.setOnClickListener(this);
    }

    private void updateTypeSelection() {
        if (currentType == TYPE_EXPENDITURE) {
            mDataBinding.tvExpenditure.setBackgroundResource(R.drawable.expenditure_sel);
            mDataBinding.tvIncome.setBackgroundColor(Color.TRANSPARENT);
            mDataBinding.pieChart.setCenterText("支出占比");
            mDataBinding.tvProportion.setText(R.string.expenditure_proportion);
            mDataBinding.tvRank.setText(R.string.expenditure_proportion);
        } else {
            mDataBinding.tvIncome.setBackgroundResource(R.drawable.income_sel);
            mDataBinding.tvExpenditure.setBackgroundColor(Color.TRANSPARENT);
            mDataBinding.pieChart.setCenterText("收入占比");
            mDataBinding.tvProportion.setText(R.string.income_proportion);
            mDataBinding.tvRank.setText(R.string.income_proportion);
        }
    }

    private void updateTimeSelection() {
        mDataBinding.tvWeek.setBackgroundColor(currentTimeRange == TIME_WEEK ?
                Color.parseColor("#FFFFFF") : Color.TRANSPARENT);
        mDataBinding.tvMonth.setBackgroundColor(currentTimeRange == TIME_MONTH ?
                Color.parseColor("#FFFFFF") : Color.TRANSPARENT);
        mDataBinding.tvYear.setBackgroundColor(currentTimeRange == TIME_YEAR ?
                Color.parseColor("#FFFFFF") : Color.TRANSPARENT);

        // 更新标题文本
        switch (currentTimeRange) {
            case TIME_WEEK:
                mDataBinding.tvText.setText(R.string.this_week);
                break;
            case TIME_MONTH:
                mDataBinding.tvText.setText(R.string.this_month);
                break;
            case TIME_YEAR:
                mDataBinding.tvText.setText(R.string.this_year);
                break;
        }
    }

    private void loadBillData() {
        // 获取当前账本数据
        int accountBookPos = SPUtil.getInt(mContext, Content.accountBook, 0);
        List<AccountBookBean> accountBookList = AppSpUtils.getAccountBookList();
        if (accountBookList != null && accountBookPos < accountBookList.size()) {
            AccountBookBean currentBook = accountBookList.get(accountBookPos);
            if (currentBook != null && currentBook.getBillBeanList() != null && currentBook.getBillBeanList().size() > 0) {
                allBills = currentBook.getBillBeanList();
                mDataBinding.llData.setVisibility(View.VISIBLE);
                updateCharts();
            } else {
                showNoData();
            }
        }
    }

    private void updateCharts() {
        // 获取过滤后的账单数据
        List<BillBean> filteredBills = getFilteredBills();

        if (filteredBills != null && filteredBills.size() > 0) {
            mDataBinding.llData.setVisibility(View.VISIBLE);
            // 更新柱状图
            updateBarChart(filteredBills);

            // 更新饼图和排名
            updatePieChartAndRank(filteredBills);
        } else {
            showNoData();
        }
    }

    private List<BillBean> getFilteredBills() {
        List<BillBean> filteredBills = new ArrayList<>();
        Calendar calendar = Calendar.getInstance();
        Date now = new Date();
        calendar.setTime(now);

        int currentYear = calendar.get(Calendar.YEAR);
        int currentMonth = calendar.get(Calendar.MONTH);
        int currentWeek = calendar.get(Calendar.WEEK_OF_YEAR);

        for (BillBean bill : allBills) {
            // 检查类型是否匹配
            if ((currentType == TYPE_EXPENDITURE && bill.isIncome()) ||
                    (currentType == TYPE_INCOME && !bill.isIncome())) {
                continue;
            }

            // 检查时间范围
            calendar.setTime(new Date(bill.getDate()));
            int billYear = calendar.get(Calendar.YEAR);
            int billMonth = calendar.get(Calendar.MONTH);
            int billWeek = calendar.get(Calendar.WEEK_OF_YEAR);

            boolean inTimeRange = false;
            switch (currentTimeRange) {
                case TIME_WEEK:
                    inTimeRange = (billYear == currentYear && billWeek == currentWeek);
                    break;
                case TIME_MONTH:
                    inTimeRange = (billYear == currentYear && billMonth == currentMonth);
                    break;
                case TIME_YEAR:
                    inTimeRange = (billYear == currentYear);
                    break;
            }

            if (inTimeRange) {
                filteredBills.add(bill);
            }
        }

        return filteredBills;
    }

    private void updateBarChart(List<BillBean> bills) {
        Map<String, Double> dateAmountMap = new HashMap<>();
        SimpleDateFormat dateFormat = null;
        List<String> xAxisLabels = new ArrayList<>();

        switch (currentTimeRange) {
            case TIME_WEEK:
                dateFormat = new SimpleDateFormat("MM-dd", Locale.getDefault());
                // 获取本周数据
                Calendar calendar = Calendar.getInstance();
                calendar.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
                for (int i = 0; i < 7; i++) {
                    String dateStr = dateFormat.format(calendar.getTime());
                    xAxisLabels.add(dateStr);
                    dateAmountMap.put(dateStr, 0.0);
                    calendar.add(Calendar.DAY_OF_MONTH, 1);
                }
                break;

            case TIME_MONTH:
                dateFormat = new SimpleDateFormat("MM-dd", Locale.getDefault());
                // 获取本月数据，只显示能被5整除的日期
                calendar = Calendar.getInstance();
                int daysInMonth = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
                calendar.set(Calendar.DAY_OF_MONTH, 1);
                for (int i = 0; i < daysInMonth; i++) {
                    int day = calendar.get(Calendar.DAY_OF_MONTH);
                    String dateStr = dateFormat.format(calendar.getTime());

                    // 只显示能被5整除的日期：5, 10, 15, 20, 25, 30
                    if (day % 5 == 0) {
                        // 只显示日期数字，如5, 10, 15等
                        xAxisLabels.add(String.valueOf(day));
                    } else {
                        xAxisLabels.add(""); // 空字符串，不显示标签
                    }
                    dateAmountMap.put(dateStr, 0.0);
                    calendar.add(Calendar.DAY_OF_MONTH, 1);
                }
                break;

            case TIME_YEAR:
                // 年度数据显示1,2,3...12
                for (int month = 1; month <= 12; month++) {
                    String monthStr = String.valueOf(month);
                    xAxisLabels.add(monthStr);
                    dateAmountMap.put(monthStr, 0.0);
                }
                break;
        }

        // 统计金额
        for (BillBean bill : bills) {
            String dateKey;
            if (currentTimeRange == TIME_YEAR) {
                Calendar cal = Calendar.getInstance();
                cal.setTime(new Date(bill.getDate()));
                dateKey = String.valueOf(cal.get(Calendar.MONTH) + 1);
            } else {
                dateKey = dateFormat.format(new Date(bill.getDate()));
            }

            double currentAmount = dateAmountMap.getOrDefault(dateKey, 0.0);
            dateAmountMap.put(dateKey, currentAmount + bill.getMoney());
        }

        // 创建柱状图数据
        List<BarEntry> entries = new ArrayList<>();
        for (int i = 0; i < xAxisLabels.size(); i++) {
            String label = xAxisLabels.get(i);
            double amount = 0.0;

            // 根据当前时间范围找到对应的金额
            if (currentTimeRange == TIME_YEAR) {
                amount = dateAmountMap.getOrDefault(String.valueOf(i + 1), 0.0);
            } else {
                // 对于月份和星期，直接获取对应的金额
                if (!label.isEmpty()) {
                    amount = dateAmountMap.getOrDefault(label, 0.0);
                } else {
                    // 对于空标签，找到对应的日期键
                    Calendar cal = Calendar.getInstance();
                    if (currentTimeRange == TIME_MONTH) {
                        cal.set(Calendar.DAY_OF_MONTH, i + 1);
                        String dateKey = dateFormat.format(cal.getTime());
                        amount = dateAmountMap.getOrDefault(dateKey, 0.0);
                    }
                }
            }
            entries.add(new BarEntry(i, (float) amount));
        }

        BarDataSet dataSet = new BarDataSet(entries, currentType == TYPE_EXPENDITURE ? "支出" : "收入");
        dataSet.setColors(currentType == TYPE_EXPENDITURE ?
                Color.parseColor("#FF6C05") : Color.parseColor("#FF6C05"));
        dataSet.setValueTextSize(10f);

        BarData barData = new BarData(dataSet);
        mDataBinding.barChart.setData(barData);

        // 设置X轴标签
        XAxis xAxis = mDataBinding.barChart.getXAxis();
        xAxis.setValueFormatter(new IndexAxisValueFormatter(xAxisLabels));

        // 设置标签显示数量
        if (currentTimeRange == TIME_YEAR) {
            xAxis.setLabelCount(12, false); // 显示所有12个月
        } else if (currentTimeRange == TIME_MONTH) {
            // 计算能被5整除的日期数量（5, 10, 15, 20, 25, 30）
            Calendar cal = Calendar.getInstance();
            int daysInMonth = cal.getActualMaximum(Calendar.DAY_OF_MONTH);
            int labelCount = daysInMonth / 5; // 5,10,15,20,25,30
            xAxis.setLabelCount(labelCount, false);
        } else {
            xAxis.setLabelCount(Math.min(xAxisLabels.size(), 10));
        }

        mDataBinding.barChart.invalidate();
    }

    private void updatePieChartAndRank(List<BillBean> bills) {
        if (bills.isEmpty()) {
            mDataBinding.pieChart.clear();
            rankAdapter.setList(new ArrayList<>());
            mDataBinding.tvRankNoData.setVisibility(View.VISIBLE);
            return;
        }

        mDataBinding.tvRankNoData.setVisibility(View.GONE);

        // 按账单类型统计
        Map<BillTypeBean, Double> typeAmountMap = new HashMap<>();
        double totalAmount = 0;

        for (BillBean bill : bills) {
            BillTypeBean type = bill.getBillTypeBean();
            double currentAmount = typeAmountMap.getOrDefault(type, 0.0);
            typeAmountMap.put(type, currentAmount + bill.getMoney());
            totalAmount += bill.getMoney();
        }

        // 创建饼图数据
        List<PieEntry> pieEntries = new ArrayList<>();
        List<RankBean> rankBeans = new ArrayList<>();

        // 如果没有数据，添加一个空数据项
        if (typeAmountMap.isEmpty()) {
            pieEntries.add(new PieEntry(100f, "暂无数据"));
        } else {
            for (Map.Entry<BillTypeBean, Double> entry : typeAmountMap.entrySet()) {
                BillTypeBean type = entry.getKey();
                double amount = entry.getValue();
                float percentage = (float) (amount / totalAmount * 100);

                pieEntries.add(new PieEntry(percentage, type.getName()));

                RankBean rankBean = new RankBean(type, (int) percentage, amount);
                rankBeans.add(rankBean);
            }
        }

        // 按金额排序
        rankBeans.sort((a, b) -> Double.compare(b.getMoney(), a.getMoney()));

        // 更新饼图中心文字为总金额，支出显示负号
        String centerText = currentType == TYPE_EXPENDITURE ?
                String.format(Locale.getDefault(), "-%.2f", totalAmount) :
                String.format(Locale.getDefault(), "%.2f", totalAmount);
        mDataBinding.pieChart.setCenterText(centerText);

        // 更新饼图
        PieDataSet dataSet = new PieDataSet(pieEntries, "");
        dataSet.setColors(typeAmountMap.isEmpty() ?
                new int[]{Color.LTGRAY} : ColorTemplate.MATERIAL_COLORS);
        dataSet.setValueTextSize(12f);
        dataSet.setValueTextColor(typeAmountMap.isEmpty() ? Color.DKGRAY : Color.BLACK);
        
        // 设置标签显示在外面
        dataSet.setXValuePosition(PieDataSet.ValuePosition.OUTSIDE_SLICE);
        dataSet.setYValuePosition(PieDataSet.ValuePosition.OUTSIDE_SLICE);
//        dataSet.setValueLinePart1OffsetPercentage(10.f);
        dataSet.setValueLinePart1Length(0.4f);
        dataSet.setValueLinePart2Length(0.4f);
        dataSet.setValueLineWidth(1f);
        dataSet.setValueLineColor(Color.BLACK);

        // 设置饼图边距，为外部标签提供空间
        mDataBinding.pieChart.setExtraOffsets(0f, 10f, 10f, 5f);
        
//        if (!typeAmountMap.isEmpty()) {
//            dataSet.setValueFormatter(new PercentFormatter(mDataBinding.pieChart));
//        } else {
//            dataSet.setValueFormatter(new com.github.mikephil.charting.formatter.ValueFormatter() {
//                @Override
//                public String getFormattedValue(float value) {
//                    return "";
//                }
//            });
//        }

        PieData pieData = new PieData(dataSet);
        pieData.setValueTextSize(10f);
        mDataBinding.pieChart.setData(pieData);
        mDataBinding.pieChart.invalidate();

        // 更新排名列表
        rankAdapter.setIncome(currentType == 1 ? true : false);
        rankAdapter.setList(rankBeans);
    }

    private void showNoData() {
        mDataBinding.llData.setVisibility(View.GONE);
        mDataBinding.barChart.clear();
        mDataBinding.pieChart.clear();
        rankAdapter.setList(new ArrayList<>());
        mDataBinding.tvRankNoData.setVisibility(View.VISIBLE);
    }
}